package com.zy.untils;


import android.os.Build;

import androidx.annotation.RequiresApi;

import com.zy.untils.base64.Base64;
import com.zy.untils.base64.OpenApiCode;
import com.zy.untils.base64.OpenApiException;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class EncryptUtilsBase64 {
//    public static String getSign(Map<String, String> params, String privateKey){
//        String signCheckContent = getSignCheckContent(params);
//        return rsa256Sign(signCheckContent, privateKey);
//    }
//
//    public static String rsa256Sign(String content, String privateKey) {
//        try {
//            //将私钥封装到java.security.PrivateKey，指定RSA私钥类型
//            PrivateKey priKey = getPrivateKeyFromPKCS8(new ByteArrayInputStream(privateKey.getBytes()));
//
//            //指定加密算法类型SHA256WithRSA
//            java.security.Signature signature = java.security.Signature
//                    .getInstance("SHA256WithRSA");
//
//            //初始化签名与私钥关系
//            signature.initSign(priKey);
//            //指定编码类型
//            signature.update(content.getBytes(StandardCharsets.UTF_8));
//            byte[] signed = signature.sign();
//            //返回签名串
//            return Base64.encodeToString(signed,Base64.DEFAULT);
//        } catch (Exception e) {
//            throw new OpenApiException(OpenApiCode.WRONG_PARAMS.getCode(), "RSA加密失败", e);
//        }
//
//    }
//
//    public static String getSignCheckContent(Map<String, String> params) {
//        if (params.isEmpty()) {
//            return null;
//        }
//        //删除sign参数，防止入参sign污染后续的加签流程
//        params.remove("sign");
//        StringBuilder content = new StringBuilder();
//        List<String> keys = new LinkedList<>(params.keySet());
//        Collections.sort(keys);
//        //拼接参数到content中
//        for (int i = 0; i < keys.size(); i++) {
//            String key = keys.get(i);
//            String value = params.get(key);
//            content.append((i == 0 ? "" : "&") + key + "=" + value);
//        }
//
//        return content.toString();
//    }
//
//    static PrivateKey getPrivateKeyFromPKCS8(InputStream ins) throws Exception {
//        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//        String key = new BufferedReader(new InputStreamReader(ins))
//                .lines().collect(Collectors.joining(System.lineSeparator()));
//        byte[] encodedKey = android.util.Base64.decode(key, android.util.Base64.DEFAULT);
//        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
//    }








    public static String getSign(Map<String, String> params, String privateKey){
        String signCheckContent = getSignCheckContent(params);
        return rsa256Sign(signCheckContent, privateKey);
    }

    public static String rsa256Sign(String content, String privateKey) {
        try {
            //将私钥封装到java.security.PrivateKey，指定RSA私钥类型
            PrivateKey priKey = getPrivateKeyFromPKCS8(new ByteArrayInputStream(privateKey.getBytes()));

            //指定加密算法类型SHA256WithRSA
            java.security.Signature signature = java.security.Signature
                    .getInstance("SHA256WithRSA");

            //初始化签名与私钥关系
            signature.initSign(priKey);
            //指定编码类型
            signature.update(content.getBytes(StandardCharsets.UTF_8));
            byte[] signed = signature.sign();
            //返回签名串
            return Base64.encodeBase64String(signed);
        } catch (Exception e) {
            throw new OpenApiException(OpenApiCode.WRONG_PARAMS.getCode(), "RSA加密失败", e);
        }

    }

    public static String getSignCheckContent(Map<String, String> params) {
        if (params.isEmpty()) {
            return null;
        }
        //删除sign参数，防止入参sign污染后续的加签流程
        params.remove("sign");
        StringBuilder content = new StringBuilder();
        List<String> keys = new LinkedList<>(params.keySet());
        Collections.sort(keys);
        //拼接参数到content中
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            content.append((i == 0 ? "" : "&") + key + "=" + value);
        }

        return content.toString();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    static PrivateKey getPrivateKeyFromPKCS8(InputStream ins) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        String key = new BufferedReader(new InputStreamReader(ins))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        byte[] encodedKey = Base64.decodeBase64(key);
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
    }
}
